package com.spboot.exts.controller;

import java.util.HashMap;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.spboot.exts.entity.Role;
import com.spboot.exts.service.PermissionService;
import com.spboot.exts.service.RoleService;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author test
 * @since 2019-08-31
 */
@Controller
@RequestMapping("/role")
public class RoleController {

	@Autowired
	RoleService roleService;

	@Autowired
	PermissionService permissionService;

	@RequiresPermissions("role_list")
	@GetMapping("/list")
	public String list(Model model) {

		model.addAttribute("roleList", roleService.list());
		return "role_list";
	}

	@PostMapping("/add")
	public String add(Role role, Long[] permId, Model model) {
		boolean f = roleService.addRoleAndPerm(role, permId);
		if (!f) {
			model.addAttribute("msg", "添加角色失败");
			model.addAttribute("permList", permissionService.list());
			return "role_add";
		}
		return "redirect:list";
	}
	/**
	 * 修改权限
	 * @param id
	 * @param permId
	 * @param model
	 * @return
	 */
	@ResponseBody
	@PostMapping("/updateAuth")
	public Object updateAuth(Long id, Long[] permId, Model model) {
		boolean f = roleService.updateRolePerm(id, permId);
		
		Map<String, Object> resMap = new HashMap<String, Object>();
		resMap.put("success", f);
		resMap.put("msg", f?"修改成功":"修改失败");
		return resMap;
	}
	

	// 跳转添加角色页面
	@GetMapping("/toadd")
	public String toadd(Model model) {
		model.addAttribute("permList", permissionService.list());
		return "role_add";
	}
	
	@GetMapping("/getauth")
	public String getauth(Long id,Model model){
		//
		model.addAttribute("id", id);
		model.addAttribute("permList", permissionService.selectRolePermission(id));
		return "role_auth";
	}

}
